import fetch from "@/utils/fetch";
export const listMixins = {
  data() {
    return {
      data: [],
      search: {
        pageNum: 1,
        pageSize: 10,
      },
      loading: true,
      scroll: false,
      noData: false,
      triggered: false,
      isReady: true,
    };
  },
  onShow: function () {
    if (this.isReady) return;
    this.getList(true);
  },
  onReady: function () {
    this.isReady = false;
    this.getList(true);
  },
  methods: {
    onRefresh() {
      if (this._freshing) return;
      this._freshing = true;
      this.triggered = true;
      this.getList(true);
      setTimeout(() => {
        this.triggered = false;
        this._freshing = false;
      }, 100);
    },
    scrollBottom(e) {
      const that = this;
      if (!that.noData) {
        that.search.pageNum = that.search.pageNum + 1;
        that.scroll = true;
        that.getList();
      }
    },
    getList(arg) {
      const that = this;
      that.$loading.open();
      if (arg) {
        that.search.pageNum = 1;
        that.data = [];
      }
      let obj = {};
      for (const key in that.search) {
        if (Object.hasOwnProperty.call(that.search, key)) {
          const element = that.search[key];
          if (element) obj[key] = element;
        }
      }
      return fetch("get", that.listUrl, obj).then(({ data }) => {
        if (that.scroll) {
          if ((data?.records || []).length === 0) {
            that.noData = true;
          } else {
            that.data.push(...data?.records);
          }
        } else {
          that.data = data?.records || [];
        }
        that.$loading.close();
      });
    },
  },
};
